package handle

import (
	"bytes"
	"errors"
	"github.com/sirupsen/logrus"
	"gocv.io/x/gocv"
	"image/jpeg"
	"net/http"
	"strings"
	"time"
)

func Thumbnail(w http.ResponseWriter, r *http.Request) {

	// 开始时间
	bt := time.Now()

	// 生成源文件地址
	url, err := parseSourceFile(r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// 打开远程视频文件
	cap, err := gocv.VideoCaptureFile(url)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// 创建一个新的Mat
	img := gocv.NewMat()

	// 读取视频的第三帧
	for i := 0; i < 3; i++ {
		cap.Read(&img)
	}

	// 将帧转换为JPEG格式的字节流
	buf := new(bytes.Buffer)
	image, err := img.ToImage()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	err = jpeg.Encode(buf, image, nil)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// 将字节流写入HTTP响应
	w.Header().Set("Content-Type", "image/jpeg")
	w.Write(buf.Bytes())

	defer func() {
		// 释放资源
		img.Close()
		cap.Close()
	}()

	//下载时间
	et := time.Since(bt)
	//格式化输出日志
	logrus.WithFields(logrus.Fields{"Url": url, "Runtime": et}).Info()

}

func parseSourceFile(r *http.Request) (string, error) {
	uri := r.RequestURI
	if uri == "" {
		return "", errors.New("uri is empty")
	}

	// 去掉"_thumbnail"
	newPath := strings.TrimSuffix(uri, "_thumbnail")
	// 合并 新的请求
	sourceUrl := "https://img.sjky.work" + newPath + "?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDMyMTUwNzgsImlhdCI6MTcwMjYxMDI3OCwianRpIjoiMSJ9.qdEzzFXzYdY4tubW0BLADXrP8ZxDxZ3VtE4_zG232Fc"
	return sourceUrl, nil
}
